package com.yjf.ljr.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.CheckEmailDataClass;
import com.yjf.ljr.dataclass.EmailCodeDataClass;
import com.yjf.ljr.dataclass.VerifySmsCodeDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UpdateEmailActivity extends IjActivity implements OnClickListener {

	private CountDownTimer time;
	@ID("etcodemessageEmail")
	private EditText mEtcodemessageEmail;
	@ID("etnewEmail")
	private EditText mEtnewEmail;
	@ID("btsendEmail")
	private Button mBtsendEmail;
	@ID("btnextEmail")
	private Button mBtnextEmail;
	@ID("tvchangeEmailMoblie")
	private TextView mTvChangeEmailMoblie;
	private String mobile;// 手机号码 不展示
	private String viewMobile;// 手机号码 展示用

	private String newMail;// 新邮箱

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_updateemail);
		initControl();
	}

	private void initControl() {
		setTitleStr("修改邮箱");
		setLeftBtnClick();
		mobile = getIntent().getStringExtra("mobile");
		viewMobile = getIntent().getStringExtra("viewMobile");
		if (!TextUtils.isEmpty(mobile)) {
			mTvChangeEmailMoblie.setText("手机号码：" + viewMobile);
		} else {
			mTvChangeEmailMoblie.setText("手机号码：暂无");
		}
		time = new TimeCount(60000, 1000);// 构造CountDownTimer对象

		mEtcodemessageEmail.setOnClickListener(this);
		mEtnewEmail.setOnClickListener(this);
		mBtnextEmail.setOnClickListener(this);
		mBtsendEmail.setOnClickListener(this);

	}

	// 获取验证码
	class SendSmsCode extends AsyncTask<Void, Void, Void> {
		private String mobile;// 电话号码
		private String mFailLog;
		private EmailCodeDataClass dateEmail = new EmailCodeDataClass();

		public SendSmsCode(String mobile) {
			this.mobile = mobile;
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			RequestObject requestObjectSms = new RequestObject();
			requestObjectSms.method = "sendSmsCode";
			requestObjectSms.map.put("mobile", mobile);
			requestObjectSms.map.put("business", "personal");

			String requestSmsUrl = RequestBuilder.build(requestObjectSms);
			try {
				IjConnect.doRequest(requestSmsUrl, dateEmail);
				if (dateEmail.code == null) {
					mFailLog = getResources().getString(R.string.loaddata_exception);
				} else if (!dateEmail.code.equals(CommonData.RESULT_SUCCESS) && !("1".equals(dateEmail.isSuccess))) {
					mFailLog = dateEmail.msg;
				}
			} catch (Exception e) {
				// TODO: handle exception
				mFailLog = getResources().getString(R.string.loaddata_exception);
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if ("-1".equals(dateEmail.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(mFailLog)) {
				showToast(mFailLog);
			} else {
				if (dateEmail.code != null && dateEmail.code.equals(CommonData.RESULT_SUCCESS)) {
					// TODO GET Verification code
					showToast(dateEmail.msg);
					// mTvUserPhone.setText("已发送短信验证码到你的手机");
					// mTvUserPhone.setTextColor(Color.parseColor("#000000"));
					// setTitleStr("验证手机");
				}
			}
		}

	}

	/******** 验证短信验证码是否正确 ******/
	class VerifySmsCodeTask extends AsyncTask<Void, Void, String> {
		private String mobile;// 手机号码
		private String code;// 验证码
		private VerifySmsCodeDataClass dc = new VerifySmsCodeDataClass();

		public VerifySmsCodeTask(String mobile, String code) {
			this.mobile = mobile;
			this.code = code;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject mObject = new RequestObject();
			mObject.method = "verifySmsCode";
			mObject.map.put("mobile", mobile);
			mObject.map.put("code", code);
			mObject.map.put("business", "personal");
			// TODO Auto-generated method stub
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);
			} else {// success
				showProgressDialog();
				new CheckEmailTask(mEtnewEmail.getText().toString(), mEtcodemessageEmail.getText().toString())
						.execute();
			}
			dismissProgressDialog();
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.btsendEmail:
			if(TextUtils.isEmpty(mobile)) {
				showToast("请绑定手机号！");
			} else {
				new SendSmsCode(mobile).execute();
				time.start();
			}	
			break;
		case R.id.btnextEmail:

			if (TextUtils.isEmpty(mEtcodemessageEmail.getText().toString())
					&& TextUtils.isEmpty(mEtnewEmail.getText().toString())) {
				showToast("请输入验证码和新邮箱地址");
				return;
			}
			if (TextUtils.isEmpty(mEtnewEmail.getText().toString())) {
				showToast("请输入新邮箱地址");
				return;
			} else {
				newMail = mEtnewEmail.getText().toString();
			}
			if (TextUtils.isEmpty(mEtcodemessageEmail.getText().toString())) {
				showToast("请输入验证码");
				return;
			}
			if (!isEmail(mEtnewEmail.getText().toString())) {
				showToast("邮箱格式不正确");
				return;
			}

			showProgressDialog();
			new VerifySmsCodeTask(mobile, mEtcodemessageEmail.getText().toString()).execute();
			break;

		default:
			break;
		}
	}

	// 判断email格式是否正确
	public boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	class CheckEmailTask extends AsyncTask<Void, Void, String> {
		private String newMail;// 新邮箱
		private String code;// 验证码
		private CheckEmailDataClass dc = new CheckEmailDataClass();

		public CheckEmailTask(String newMail, String code) {
			this.newMail = newMail;
			this.code = code;
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestObject mRequestObject = new RequestObject();
			mRequestObject.method = "updateMail";
			mRequestObject.map.put("newMail", newMail);
			mRequestObject.map.put("code", code);
			return requestDataAndGetErrorMsg(mRequestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);
			} else {// success
				showToast(dc.msg);
				Intent intent = new Intent();
				intent.putExtra("changemail", true);
				intent.putExtra("newemail", newMail);

				setResult(RESULT_OK, intent);
				finish();

			}
		}
	}

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			mBtsendEmail.setText("重新发送");
			mBtsendEmail.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			mBtsendEmail.setClickable(false);
			mBtsendEmail.setText(millisUntilFinished / 1000 + "秒");
		}
	}

}
